/**
 * 顺序表实现的成绩管理
 * 使用数组存储学生成绩信息
 */
public class ArrayGradeManagement implements GradeManagementInterface {
    private Student[] students; // 存储学生的数组
    private int count; // 当前学生人数
    private int capacity; // 数组容量

    /**
     * 构造方法：指定初始容量
     * 
     * @param capacity 初始容量
     */
    public ArrayGradeManagement(int capacity) {
        this.capacity = capacity;
        this.students = new Student[capacity];
        this.count = 0;
    }

    /**
     * 默认构造方法：容量为50
     */
    public ArrayGradeManagement() {
        this(50);
    }

    @Override
    public boolean isEmpty() {
        return count == 0;
    }

    @Override
    public boolean isFull() {
        return count == capacity;
    }

    @Override
    public int size() {
        return count;
    }

    /**
     * 扩展数组容量
     */
    private void expandCapacity() {
        int newCapacity = capacity * 2;
        Student[] newArray = new Student[newCapacity];
        System.arraycopy(students, 0, newArray, 0, count);
        students = newArray;
        capacity = newCapacity;
    }

    @Override
    public boolean add(Student student) {
        if (student == null) {
            return false;
        }
        // 检查是否已存在相同学号的学生
        if (findById(student.getStudentId()) != null) {
            System.out.println("学号 " + student.getStudentId() + " 已存在，添加失败");
            return false;
        }
        // 如果数组已满，扩展容量
        if (isFull()) {
            expandCapacity();
        }
        students[count++] = student;
        return true;
    }

    @Override
    public Student findById(String studentId) {
        for (int i = 0; i < count; i++) {
            if (students[i].getStudentId().equals(studentId)) {
                return students[i];
            }
        }
        return null;
    }

    @Override
    public Student get(int index) {
        if (index < 0 || index >= count) {
            throw new IndexOutOfBoundsException("索引越界: " + index);
        }
        return students[index];
    }

    @Override
    public boolean remove(String studentId) {
        for (int i = 0; i < count; i++) {
            if (students[i].getStudentId().equals(studentId)) {
                // 将后面的元素前移
                for (int j = i; j < count - 1; j++) {
                    students[j] = students[j + 1];
                }
                students[count - 1] = null; // 清空最后一个元素
                count--;
                return true;
            }
        }
        return false;
    }

    @Override
    public void sortByScore() {
        // 使用冒泡排序（按综合成绩从高到低）
        for (int i = 0; i < count - 1; i++) {
            for (int j = 0; j < count - 1 - i; j++) {
                if (students[j].getComprehensiveScore() < students[j + 1].getComprehensiveScore()) {
                    // 交换
                    Student temp = students[j];
                    students[j] = students[j + 1];
                    students[j + 1] = temp;
                }
            }
        }
        // 更新排名
        for (int i = 0; i < count; i++) {
            students[i].setRank(i + 1);
        }
    }

    @Override
    public void evaluateScholarship(double firstPrizeRatio, double secondPrizeRatio, double thirdPrizeRatio) {
        // 先按成绩排序
        sortByScore();

        // 计算各等级人数（向下取整）
        int total = count;
        int firstPrizeCount = (int) Math.floor(total * firstPrizeRatio);
        int secondPrizeCount = (int) Math.floor(total * secondPrizeRatio);
        int thirdPrizeCount = (int) Math.floor(total * thirdPrizeRatio);

        // 评定奖学金
        for (int i = 0; i < count; i++) {
            if (i < firstPrizeCount) {
                students[i].setScholarship("一等奖");
            } else if (i < firstPrizeCount + secondPrizeCount) {
                students[i].setScholarship("二等奖");
            } else if (i < firstPrizeCount + secondPrizeCount + thirdPrizeCount) {
                students[i].setScholarship("三等奖");
            } else {
                students[i].setScholarship("无");
            }
        }
    }

    @Override
    public void displayAll() {
        if (isEmpty()) {
            System.out.println("成绩表为空");
            return;
        }
        System.out.println("========== 所有学生成绩信息 ==========");
        System.out.println(String.format("%-8s %-6s %-8s %-15s %-10s %-6s %-10s",
                "学号", "姓名", "班级", "各科成绩", "综合成绩", "排名", "奖学金"));
        System.out.println("-----------------------------------------------------------");
        for (int i = 0; i < count; i++) {
            Student s = students[i];
            StringBuilder scoresStr = new StringBuilder("[");
            double[] scores = s.getCourseScores();
            for (int j = 0; j < scores.length; j++) {
                scoresStr.append(String.format("%.2f", scores[j]));
                if (j < scores.length - 1) {
                    scoresStr.append(", ");
                }
            }
            scoresStr.append("]");
            System.out.println(String.format("%-8s %-6s %-8s %-15s %-10.2f %-6d %-10s",
                    s.getStudentId(), s.getName(), s.getClassName(),
                    scoresStr.toString(), s.getComprehensiveScore(),
                    s.getRank(), s.getScholarship()));
        }
        System.out.println("==========================================");
    }

    @Override
    public void displayScholarshipWinners() {
        if (isEmpty()) {
            System.out.println("成绩表为空");
            return;
        }
        System.out.println("========== 获奖学生名单 ==========");
        boolean hasWinner = false;
        for (int i = 0; i < count; i++) {
            if (!students[i].getScholarship().equals("无")) {
                hasWinner = true;
                System.out.println(students[i].toString());
            }
        }
        if (!hasWinner) {
            System.out.println("暂无获奖学生");
        }
        System.out.println("====================================");
    }

    @Override
    public void clear() {
        for (int i = 0; i < count; i++) {
            students[i] = null;
        }
        count = 0;
    }

    @Override
    public void merge(GradeManagementInterface other) {
        if (other == null) {
            return;
        }
        int otherSize = other.size();
        for (int i = 0; i < otherSize; i++) {
            Student student = other.get(i);
            // 创建新学生对象，避免引用冲突
            Student newStudent = new Student(
                    student.getStudentId(),
                    student.getName(),
                    student.getClassName(),
                    student.getCourseScores());
            add(newStudent);
        }
    }
}

